package com.imooc.spark.streaming.kafka

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010._
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

/**
  * http://spark.apache.org/docs/latest/streaming-kafka-0-10-integration.html
  *
  * @description Spark Streaming + Kafka-0.10集成
  * @author yuyon26@126.com
  * @date 2018/10/27 0:19
  */
object KafkaStreamingWordCountTest {

  def main(args: Array[String]): Unit = {

    if (args.length != 3) {
      System.err.println("Usage: KafkaStreamingWordCountTest <bootstrapServers> <groupId> <topics>")
      System.exit(1)
    }

    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("KafkaStreamingWordCountTest")
    val ssc = new StreamingContext(sparkConf, Seconds(5))
    ssc.sparkContext.setLogLevel("ERROR")

    val Array(bootstrapServers, groupId, topics) = args

    val kafkaParams = Map[String, Object](
      "bootstrap.servers" -> bootstrapServers,
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> groupId,
      "auto.offset.reset" -> "latest",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )

    val message = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics.split(",").toArray, kafkaParams)
    )

    message.map(record => record.value)
      .flatMap(_.split(" "))
      .map((_, 1))
      .reduceByKey(_ + _)
      .print()

    ssc.start()
    ssc.awaitTermination()
  }
}
